package bjut.zrpc.core.optimization.zookeeper;

import bjut.zrpc.core.optimization.bean.ZRpcServiceBean;
import bjut.zrpc.core.optimization.constant.ZRpcConstant;
import bjut.zrpc.core.optimization.interfaces.ServiceRegistry;
import bjut.zrpc.core.optimization.utils.CuratorUtil;
import org.apache.curator.framework.CuratorFramework;

import java.net.InetSocketAddress;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/23 21:41
 */
public class ZookeeperRegistry implements ServiceRegistry {

    private static final Set<String> registeredServiceSet = ConcurrentHashMap.newKeySet();
    private static final ConcurrentHashMap<String, Object> REGISTERED_SERVICE_MAP = new ConcurrentHashMap<>();

    @Override
    public void registerService(ZRpcServiceBean zRpcServiceBean) {

        addService(zRpcServiceBean);

        InetSocketAddress inetSocketAddress = new InetSocketAddress(ZRpcConstant.SERVICE_HOST, ZRpcConstant.NETTY_SERVER_PORT);
        String serverAddress = ZRpcConstant.ZRPC_ROOT_PATH + zRpcServiceBean.getRpcServiceName() + inetSocketAddress;
        CuratorFramework zkClient = CuratorUtil.getZkClient();

        doRegisterService(zkClient, serverAddress);

    }


    @Override
    public void addService(ZRpcServiceBean zRpcServiceBean) {

        String rpcServiceName = zRpcServiceBean.getRpcServiceName();

        if (registeredServiceSet.contains(rpcServiceName)) return;

        registeredServiceSet.add(rpcServiceName);
        REGISTERED_SERVICE_MAP.put(rpcServiceName, zRpcServiceBean.getService());

    }

    @Override
    public Object getService(String serviceName) {
        Object service = REGISTERED_SERVICE_MAP.get(serviceName);
        if (service == null) throw new RuntimeException(" no has such service  " + serviceName);
        return service;
    }

    private void doRegisterService(CuratorFramework zkClient, String serverAddress) {
        CuratorUtil.createServicePath(zkClient, serverAddress);
    }





}
